package com.qu.waibao.my.activity;

import android.Manifest;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.othershe.nicedialog.BaseNiceDialog;
import com.othershe.nicedialog.NiceDialog;
import com.othershe.nicedialog.ViewConvertListener;
import com.othershe.nicedialog.ViewHolder;
import com.qu.waibao.AppConfig;
import com.qu.waibao.R;
import com.qu.waibao.base.BaseActivity;
import com.qu.waibao.base.BaseRecyclerAdapter;
import com.qu.waibao.bean.Hexiao;
import com.qu.waibao.home.adpater.KefuAdapter;
import com.qu.waibao.interf.XnetCallBack;
import com.qu.waibao.my.adapter.HexaioAdapter;
import com.qu.waibao.network.ActionUtil;
import com.qu.waibao.network.NetManager;
import com.qu.waibao.utils.GsonUtil;
import com.qu.waibao.utils.TDevice;
import com.qu.waibao.utils.ToastUtil;
import com.qu.waibao.widget.RecyclerRefreshLayout;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class HexiaoActivity extends BaseActivity implements View.OnClickListener,
        RecyclerRefreshLayout.SuperRefreshLayoutListener{
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.iv_publish)
    ImageView iv_publish;
    @BindView(R.id.mRecyclerRefreshLayout)
    RecyclerRefreshLayout mRecyclerRefreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.tv_all_total)
    TextView tv_all_total;
    @BindView(R.id.et_code)
    EditText et_code;
    private HexaioAdapter adapter;
    private boolean isRefreshing = true;
    private int pageNum = 1;
    private String dates = "";
    private TimePickerView timePickView;
    @Override
    protected int getContentView() {
        return R.layout.activity_hexiao;
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        tv_title.setText("优惠卷核销");
        iv_publish.setVisibility(View.GONE);
        mRecyclerRefreshLayout.setColorSchemeResources(R.color.colorPrimaryDark);
        mRecyclerRefreshLayout.setSuperRefreshLayoutListener(this);

    }

    @Override
    protected void initData() {
        super.initData();
        adapter = new HexaioAdapter(this, BaseRecyclerAdapter.ONLY_FOOTER);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setNestedScrollingEnabled(false);
        recyclerView.setAdapter(adapter);
        if(adapter.getItems().size() == 0){
            mRecyclerRefreshLayout.setRefreshing(true);
            onRefreshing();
        }
    }

    @OnClick({R.id.ll_back,R.id.tv_hexiao,R.id.tv_select_time})
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ll_back:
                finish();
                break;
            case R.id.tv_select_time:
                initTimeOptionPick();
                timePickView.show();
                break;
            case R.id.tv_hexiao:
                String code = et_code.getText().toString();
                if(TextUtils.isEmpty(code)){
                    ToastUtil.show(this,"请输入优惠卷的编码");
                    return;
                }
                hexiao(code);
                break;
        }
    }

    public void requestData(){
        Map<String,String> map = new HashMap<>();
        map.put("action", ActionUtil.quan_checklist_get);
        map.put("userid", AppConfig.getString("userid"));
        map.put("date_tj",dates);
        map.put("pagenum",pageNum+"");
        NetManager.getInstance().request(this, map, false, new XnetCallBack() {
            @Override
            public void onSuccess(String result, String msg) {
                Hexiao hexiao = GsonUtil.createGson().fromJson(result,Hexiao.class);
                tv_all_total.setText("总共   ¥"+hexiao.getTotal_all());
                if(isRefreshing){
                    adapter.clear();
                    adapter.addAll(hexiao.getTotal_month());
                    if(hexiao.getTotal_month().size() < 12){
                        adapter.setState(BaseRecyclerAdapter.STATE_NO_MORE,true);
                    }
                }else {
                    adapter.addAll(hexiao.getTotal_month());
                    if(hexiao.getTotal_month().size() < 12){
                        adapter.setState(BaseRecyclerAdapter.STATE_NO_MORE,true);
                    }
                    if(hexiao.getTotal_month().size() == 0){
                        pageNum--;
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
               if(pageNum > 1){
                   pageNum--;
                   onComplate();
               }
            }

            @Override
            public void onFinished() {
                onComplate();
            }
        });
    }

    public void onComplate(){
        mRecyclerRefreshLayout.onComplete();
        isRefreshing = false;
    }

    @Override
    public void onRefreshing() {
        isRefreshing = true;
        pageNum = 1;
        requestData();
    }

    @Override
    public void onLoadMore() {
        isRefreshing = false;
        pageNum++;
        adapter.setState(BaseRecyclerAdapter.STATE_LOAD_MORE,true);
        requestData();
    }

    public void hexiao(String myquancode){
        Map<String,String> map = new HashMap<>();
        map.put("action", ActionUtil.quan_check_set);
        map.put("userid", AppConfig.getString("userid"));
        map.put("myquancode",myquancode);
        RequestParams params = NetManager.getUrl(map);
        x.http().post(params, new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject object = new JSONObject(result);
                    if(object.optInt("status") == 1){
                        onRefreshing();
                        NiceDialog.init()
                                .setLayoutId(R.layout.hexiao_dialog_layout)     //设置dialog布局文件
                                .setConvertListener(new ViewConvertListener() {     //进行相关View操作的回调
                                    @Override
                                    public void convertView(ViewHolder holder, final BaseNiceDialog dialog) {
                                        holder.setText(R.id.tv_warn,"核销成功");
                                        ((ImageView)holder.getView(R.id.iv_error)).setImageResource(R.drawable.tx_chenggong);
                                        holder.setOnClickListener(R.id.iv_delete, new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                dialog.dismiss();
                                            }
                                        });
                                    }
                                })
                                .setMargin(16)
                                .setDimAmount(0.3f)     //调节灰色背景透明度[0-1]，默认0.5f
                                .setShowBottom(false)     //是否在底部显示dialog，默认flase
                                .setOutCancel(true)     //点击dialog外是否可取消，默认true
                                .show(getSupportFragmentManager());     //显示dialog
                    }else {
                        NiceDialog.init()
                                .setLayoutId(R.layout.hexiao_dialog_layout)     //设置dialog布局文件
                                .setConvertListener(new ViewConvertListener() {     //进行相关View操作的回调
                                    @Override
                                    public void convertView(ViewHolder holder, final BaseNiceDialog dialog) {
                                        holder.setText(R.id.tv_warn,"核销失败");
                                        holder.setOnClickListener(R.id.iv_delete, new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                dialog.dismiss();
                                            }
                                        });
                                    }
                                })
                                .setMargin(16)
                                .setDimAmount(0.3f)     //调节灰色背景透明度[0-1]，默认0.5f
                                .setShowBottom(false)     //是否在底部显示dialog，默认flase
                                .setOutCancel(true)     //点击dialog外是否可取消，默认true
                                .show(getSupportFragmentManager());     //显示dialog
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    public void initTimeOptionPick(){
        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        Calendar endDate = Calendar.getInstance();
        //正确设置方式 原因：注意事项有说明
        startDate.set(2000,0,1);
        endDate.set(2020,11,31);
        timePickView = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                dates = getTime(date);
                isRefreshing = true;
                requestData();
            }
        })
                .setType(new boolean[]{true, true, false, false, false, false})// 默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setTitleText("时间选择")//标题
                .setSubCalSize(14)//确定和取消文字大小
                .setTitleSize(16)//标题文字大小
                .setTitleColor(Color.parseColor("#333333"))//标题文字颜色
                .setSubmitColor(Color.parseColor("#f29f1b"))//确定按钮文字颜色
                .setCancelColor(Color.parseColor("#f29f1b"))//取消按钮文字颜色
                .setTitleBgColor(Color.parseColor("#F1F1F1"))//标题背景颜色 Night mode
                .setBgColor(Color.parseColor("#FFFFFF"))//滚轮背景颜色 Night mode
                .setDate(selectedDate)
                .setRangDate(startDate,endDate)//起始终止年月日设定
                .setLabel("","","","","","")//默认设置为年月日时分秒
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .isDialog(true)//是否显示为对话框样式
                .build();
    }

    public String getTime(Date date){
        if(date != null) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");
            String time = simpleDateFormat.format(date);
            return time;
        }
        return "";
    }
}
